﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace FileManager_Server.Utility
{

    public class ServerLocalFile
    {
        private static string ClientUpdateFolder
        {
            get { return Path.Combine(Application.StartupPath, GlobalString.System_Config_String.ClientUpdateFolderName); }
        }

        public static void InitFolderUpdateFolder()
        {
            if (!Directory.Exists(ClientUpdateFolder))
                Directory.CreateDirectory(ClientUpdateFolder);
        }

        private static string ClientUpdateInfoFile
        {
            get { return Path.Combine(Application.StartupPath, GlobalString.System_Config_String.ClientApplicationVersionFile); }
        }

        public static void SaveApplicationInfo(ClientApplicationInfoLocal applicationInfoLocal)
        {
            try
            {
                var resultByte = ObjectToByteArray(applicationInfoLocal);
                File.WriteAllBytes(ClientUpdateInfoFile, resultByte);
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("SaveApplicationInfo has Problem",ex);
                MessageBox.Show("程序异常，请联系管理员!");
            }
        }

        public static ClientApplicationInfoLocal ReadApplicationInfo()
        {
            try
            {
                if (!File.Exists(ClientUpdateInfoFile)) return null;
                var allbytes = File.ReadAllBytes(ClientUpdateInfoFile);
                var result = ByteArrayToObject(allbytes) as ClientApplicationInfoLocal;
                return result;
            }
            catch (Exception ex)
            {
                File.WriteAllText(ClientUpdateInfoFile, string.Empty);
                LogLoader.Instance.Log.Error("ReadApplicationInfo has Problem", ex);
                MessageBox.Show("程序异常，请联系管理员!");
                return null;
            }
        }

        // Convert an object to a byte array
        private static byte[] ObjectToByteArray(Object obj)
        {
            if (obj == null)
                return null;
            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
        // Convert a byte array to an Object
        private static Object ByteArrayToObject(byte[] arrBytes)
        {
            var memStream = new MemoryStream();
            var binForm = new BinaryFormatter();
            memStream.Write(arrBytes, 0, arrBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            var obj = binForm.Deserialize(memStream);
            return obj;
        }
    }

    [Serializable]
    public class ClientApplicationInfoLocal
    {
        public string ClientVersion { get; set; }
        public byte[] Infomation { get; set; }
    }
}